import { listTreeByUser } from '@/api/modules/sys/menu'
import router from '@/router'
import { resetRouter } from '@/router'

const state = {
  menus: [],
  menuLoaded: false
}

const mutations = {
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_LOADED: (state, loaded) => {
    state.menuLoaded = loaded
  }
}

const actions = {
  /* 重新加载菜单和路由 */
  reloadMenuAndRoute({ commit, state }) {
    commit('SET_LOADED', false)
  },
  /* 获取当前用户关联的菜单 */
  getMenus({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.menuLoaded) {
        resolve()
        return
      }
      listTreeByUser().then(res => {
        const menus = res.data
        const dynamicRoutes = addSyncRoutes(menus)
        // 重置下路由
        resetRouter()
        router.options.routes[0].children = router.options.routes[0].children.concat(dynamicRoutes)
        router.options.routes.push({
          path: '*', redirect: '/404'
        })
        router.addRoutes(router.options.routes)
        commit('SET_MENUS', menus)
        commit('SET_LOADED', true)
        console.log('加载路由成功')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

function addSyncRoutes(menuList = [], routes = []) {
  menuList.forEach(menu => {
    if (menu.children && menu.children.length) {
      addSyncRoutes(menu.children, routes)
    } else {
      // 创建路由配置
      const route = {
        path: menu.url,
        name: menu.name,
        component: () => import(`@/views${menu.url}`),
        meta: {
          title: menu.name
        }
      }
      routes.push(route)
    }
  })
  return routes
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

